package me.chan.helper;

import me.chan.annotation.Inject;
import me.chan.util.ReflectUtil;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * Created by JanGin on 2017/6/19.
 */
public class IocHelper {

    static {
        //obtains all the classes in this application
        Map<Class<?>, Object> beanMap = BeanHelper.getGlobalBeansMap();

        if (MapUtils.isNotEmpty(beanMap)) {
            for (Map.Entry<Class<?>, Object> beanEntry :beanMap.entrySet()) {
                Class<?> clazz = beanEntry.getKey();
                Object obj = beanEntry.getValue();
                Field[] fields = clazz.getDeclaredFields();
                if (ArrayUtils.isNotEmpty(fields)) {
                    for (Field beanField : fields) {
                        //find the serviceBean
                        if (beanField.isAnnotationPresent(Inject.class)) {
                            Class<?> fieldClass = beanField.getType();
                            Object fieldInstanceClass = beanMap.get(fieldClass);
                            if (fieldInstanceClass != null) {
                                //set the field into the instance object of Class<?>
                                ReflectUtil.setField(obj, beanField, fieldInstanceClass);
                            }

                        }
                    }
                }
            }

        }
    }
}
